package com.itita.ww2.model.item;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itita.ww2.data.ItemConfig;
import com.itita.ww2.model.item.enums.ItemPrimaryType;
import com.itita.ww2.model.item.prop.ItemProp;
import com.itita.ww2.utils.UUIDGenerator;

/**
 * 物品Builder
 * @author NorthLan
 *
 */
public class ItemBuilder {
	private static final Logger logger = LoggerFactory.getLogger(ItemBuilder.class);

	private String uuid = ""; // 唯一ID
	private String itemId;
	//
	private boolean used; // ItemEquip专用
	// 
	private boolean genericUUID = false;

	public ItemBuilder setUUID(String uuid) {
		this.uuid = uuid;
		return this;
	}

	public ItemBuilder genericUUID() {
		this.genericUUID = true;
		return this;
	}

	public ItemBuilder setUsed(boolean used) {
		this.used = used;
		return this;
	}

	public ItemBuilder setItemId(String itemId) {
		this.itemId = itemId;
		return this;
	}

	public AbstractItem build() {
		if (this.itemId == null) {
			logger.error("ItemId is null");
			return null;
		}
		return buildByItemId();
	}

	private AbstractItem buildByItemId() {
		ItemPrimaryType type = ItemPrimaryType.idValueOf(itemId);
		if (type == ItemPrimaryType.UNKNOWN) {
			logger.error("Error ItemId: {}", this.itemId);
			return null;
		}
		AbstractItem ref = null;
		if (genericUUID) {
			this.uuid = UUIDGenerator.nextItemId();
		}

		int p1 = ItemConfig.getItemParam1(itemId);
		int p2 = ItemConfig.getItemParam2(itemId);
		boolean useable = ItemConfig.isItemUseable(itemId);
		int ep = ItemConfig.getItemEffParam(itemId);
		boolean compositable = ItemConfig.isItemCompositable(itemId);
		//
		switch (type) {
		case EQUIPMENT:
			ref = new ItemEquip(itemId, p1, p2, useable, ep, ItemConfig.getItemLv(itemId),
					ItemConfig.getItemNextId(itemId), ItemConfig.getItemComResource(itemId),
					ItemConfig.getItemComTable(itemId), compositable, used);
			break;
		case BLUEPRINT:
			ref = new ItemBlueprint(itemId, p1, p2, useable, ep, ItemConfig.getEffValueAsInt(itemId), compositable);
			break;
		case ELEMENT:
			ref = new ItemElement(itemId, p1, p2, useable, ep, compositable);
			break;
		case PROP:
			{
				Object effValue = null;
				if (ep == 1) {
					effValue = ItemConfig.getEffValueAsInt(itemId);
				} else {
					effValue = ItemConfig.getEffValueAsString(itemId);
				}
				ref = new ItemProp(itemId, p1, p2, useable, ep, effValue, compositable);
			}
			break;
		case UNKNOWN:
			logger.error("Unknown item: {}", this.itemId);
			break;
		}
		if (ref != null) {
			ref.setUuid(uuid);
		}
		return ref;
	}
}
